package com.util.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: hechaobo
 * @Date: 2023/9/6
 **/
public class Listener extends AnalysisEventListener<Map<Integer,String>> {
    Map<String,Integer> head=new HashMap<String,Integer>();
    private Map<Integer,String> data=new HashMap<Integer,String>();
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        headMap.entrySet().forEach(e->{
            head.put(e.getValue(),e.getKey());
        });
    }
    @Override
    public void invoke(Map<Integer, String> integerStringMap, AnalysisContext analysisContext) {
        this.data=integerStringMap;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if(exception instanceof NoFieldException){
            throw exception;
        }
    }

    /**
     * @param name
     * @return {@link String}
     */
    public String getByColName(String name){
        if(!head.containsKey(name)){
            throw new NoFieldException(name+"字段不存在");
        }
        return data.get(head.get(name));
    }
}
